package com.gzist.zzchatroomserver.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * MybatisPlus配置类
 */
@Configuration
@MapperScans({
        @MapperScan("com.gzist.zzchatroomserver.mapper")
})
public class MybatisPlusConfig {

    @Autowired
    private DataSource dataSource;

    /**
     * 分页插件
     * 根据数据库类型构建一个拦截器来处理分页
     * @return MybatisPlusInterceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() throws SQLException {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(getDbType()));
        // 你可以添加其他拦截器比如防止全表更新和删除
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        return interceptor;
    }

    /**
     * 根据 DataSource 自动推断数据库类型
     * @return DbType
     */
    private DbType getDbType() throws SQLException {
        String url = dataSource.getConnection().getMetaData().getURL();
        if (url.contains("mysql")) {
            return DbType.MYSQL;
        } else if (url.contains("postgresql")) {
            return DbType.POSTGRE_SQL;
        } else if (url.contains("oracle")) {
            return DbType.ORACLE;
        } else if (url.contains("sqlserver")) {
            return DbType.SQL_SERVER;
        } else if (url.contains("h2")) {
            return DbType.H2;
        } else if (url.contains("sqlite")) {
            return DbType.SQLITE;
        } else {
            throw new IllegalArgumentException("不支持的数据库类型，请检查连接字符串");
        }
    }
}
